<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
      </connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <!-- <el-tab-pane label="按所在分区统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="按所在分区统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="按所在校区统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie2Data" @pieclick="echartsClick" title="按所在校区统计分析"/>
            </el-col>
          </el-tab-pane> -->
          <el-tab-pane label="按资产名称统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按资产名称统计分析"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <!-- <el-table-column label="所在分区" prop="PrimArea" width="120" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所在校区" show-overflow-tooltip prop="SchoolName" width="140" align="left">
            <template slot-scope="{row}">
              <span>{{ row.SchoolName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="240"  align="left">
            <template slot-scope="{row}">
              <span>{{ row.DeviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="检测时间" show-overflow-tooltip prop="TransTime" width="160" align="left"></el-table-column>
          <el-table-column label="核查项目" show-overflow-tooltip prop="BlID" align="left">
            <template slot-scope="{row}">
              <span>{{ findBaselineLabel(row.BlID) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="合规结论" show-overflow-tooltip prop="NeedFix" width="120" align="left">
            <template slot-scope="{row}">
              <span :style="{color: row.NeedFix === 0 ? '#67C23A' : '#F56C6C'}">{{row.NeedFix === 0 ? '合规' : '不合规'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="描述信息" show-overflow-tooltip prop="Descp"  align="left"></el-table-column>
          <el-table-column label="操作" align="left" width="120px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="changeMailGlobal(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="详情"
      :visible.sync="logDialog"
      v-el-drag-dialog
      width="1000px">
        <el-descriptions class="margin-top" :column="2"  border>
          <!-- <el-descriptions-item label="所在分区">{{ logList.PrimArea }}/{{ logList.SecondArea }}</el-descriptions-item> -->
          <el-descriptions-item label="从属部门">{{ logList.Department }}</el-descriptions-item>
          <!-- <el-descriptions-item label="校区名称">{{ logList.SchoolName }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="校区唯一编码">{{ logList.SchoolID }}</el-descriptions-item> -->
          <el-descriptions-item label="资产名称">{{ logList.DeviceName }}</el-descriptions-item>
          <el-descriptions-item label="资产唯一编码">{{ logList.DeviceID }}</el-descriptions-item>
          <el-descriptions-item label="检测时间">{{ logList.TransTime }}</el-descriptions-item>
          <el-descriptions-item label="核查项目"> 
                <span>{{ findBaselineLabel(logList.BlID) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="合规结论"> 
                <span :style="{color: logList.NeedFix === 0 ? '#67C23A' : '#F56C6C'}">{{logList.NeedFix === 0 ? '合规' : '不合规'}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="描述信息" :span="2">{{ logList.Descp }}</el-descriptions-item>
          <el-descriptions-item label="修复建议" :span="2">{{ findBaselineFixScheme(logList.BlID) }}</el-descriptions-item>
        </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="logDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { parseTime, formatTime2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按资产名称统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      logDialog: false,
      logList: [],
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      tableData:[],
      BaselineResultList: [],
      searchform:{},
      options:{},
      searchobj: {},
      formOptions: [
        {
          col: 6,
          hidden: false,
          label: "检测项目", // label文字
          prop: "BlID", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择检测项目", // elementui组件属性
          options: [],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.BlID = val
            },
          },
        },
        {
          col: 6,
          hidden: false,
          label: "合规性", // label文字
          prop: "BaselineNeedFix", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择合规性", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '合规', value: 1 },
            { label: '不合规', value: 2 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.BaselineNeedFix = val
            },
          },
        },
        {
          col: 8,
          label: "资产选择",
          prop:"DeviceName",
          element: "el-select",
          initValue: "",
          placeholder: "请选择资产",
          options:[],
          events: {
            input(val) {
              that.searchform.DeviceName = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'SumCount', 10)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.CenterGetDevice()
    this.GetBaselineFixSet()
  },
  methods: {
    async CenterGetDevice(){
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000000
        },
        Filter:{
          Status: 0,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let assetList = []
      res.Data.map(item => {
        assetList.push({ label: item.DeviceName, value: item.DeviceID })
      })
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = assetList
        }
      })
    },
    // 获取子节点的资产
    async lazyLoad(node, resolve){
      if(node.level < 4){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SchoolName: node.label,
          }
        }
        const res = await connrequest('CenterGetDevice', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.DeviceName, value: item.DeviceID, level: 5, children: undefined} )
        })
        resolve(arr) 
      }
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
              children: secondArea.School.map(School => ({
                SubClass: School.SchoolName,
                value: School.SchoolID,
                level: 4,
              }))
          }))
        }))
      }
    },
    // 获取资产树
    async GetDeviceStatusSumTree() {
      const res = await connrequest('GetDeviceStatusSumTree')
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = [this.transformData(res.Data)]
        }
      })
    },
    async changeMailGlobal(row){
      this.logList = {...row}
      // console.log( this.logList)
      this.logDialog = true
    },
    async GetBaselineFixSet(){
      const res = await connrequest('GetBaselineFixSet')
      let arr = []
      res.Data.BaselineResult.map(item => {
        arr.push({ label: item.Subject, value: item.id * 1, FixScheme: item.FixScheme })
      })
      this.formOptions.map( item => {
        if(item.label === '检测项目'){
          item.options = [{label: '全部', value: '', FixScheme: ''}, ...arr]
        }
      })
      this.BaselineResultList = arr
    },
    findBaselineLabel(BlID) {
      const baselineItem = this.BaselineResultList.find(item => item.value === BlID);
      return baselineItem ? baselineItem.label : '';
    },
    findBaselineFixScheme(BlID) {
      const baselineItem = this.BaselineResultList.find(item => item.value === BlID);
      return baselineItem ? baselineItem.FixScheme : '';
    },
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '按所在分区统计分析':
          this.GetDeviceRealBaselineCheckSumGroupByArea()
          break;
        case '按所在校区统计分析':
          this.GetDeviceRealBaselineCheckSumGroupBySchool()
          break;default:
          this.GetDeviceRealBaselineCheckSumGroupByDevice()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '按所在分区统计分析'){
        this.searchobj = { PrimArea: val.split('_')[0], SecondArea: val.split('_')[1] }
        this.GetEventLog(this.searchobj)
      }else if(title === '按所在校区统计分析'){
        this.searchobj = { SchoolName: val }
        this.GetEventLog(this.searchobj)
      }else{
        this.searchobj = { DeviceName: val }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '按所在分区统计分析':
          this.GetDeviceRealBaselineCheckSumGroupByArea()
          break;
        case '按所在校区统计分析':
          this.GetDeviceRealBaselineCheckSumGroupBySchool()
          break;default:
          this.GetDeviceRealBaselineCheckSumGroupByDevice()
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          DeviceID: this.searchform.DeviceName,
          BlID: this.searchform.BlID * 1,
          BaselineNeedFix: this.searchform.BaselineNeedFix,
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceRealBaselineCheck', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging?.TotalCount
    },
    // 按所在分区统计分析
    async GetDeviceRealBaselineCheckSumGroupByArea(){
      let arr = []
      const data = {
        Filter:{
          DeviceID: this.searchform.DeviceName,
          BlID: this.searchform.BlID,
          BaselineNeedFix: this.searchform.BaselineNeedFix,
        }
      }
      const res = await connrequest('GetDeviceRealBaselineCheckSumGroupByArea', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 按所在校区统计分析
    async GetDeviceRealBaselineCheckSumGroupBySchool(){
      let arr = []
      const data = {
        Filter:{
          DeviceID: this.searchform.DeviceName,
          BlID: this.searchform.BlID,
          BaselineNeedFix: this.searchform.BaselineNeedFix,
        }
      }
      const res = await connrequest('GetDeviceRealBaselineCheckSumGroupBySchool', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie2Data = arr
    },
    // 按事件资产统计分析
    async GetDeviceRealBaselineCheckSumGroupByDevice(){
      let arr = []
      const data = {
        Filter:{
          DeviceID: this.searchform.DeviceName,
          BlID: this.searchform.BlID,
          BaselineNeedFix: this.searchform.BaselineNeedFix,
        }
      }
      const res = await connrequest('GetDeviceRealBaselineCheckSumGroupByDevice', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie3Data = arr
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "状态检测" || item.label === "检测项目"){
          item.initValue = ''
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'NeedFix', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
::v-deep .el-descriptions-item__label.is-bordered-label{
  width: 200px;
}
</style>